/*
 * @Author: sunzhijun
 * @LastEditors: sunzhijun
 * @Date: 2019-03-23 14:43:10
 * @LastEditTime: 2019-03-24 20:14:11
 */
import React, { Component, PureComponent } from 'react';
import ReactDOM from 'react-dom';
import { high, createPage, base, toast, promptBox, cacheTools, getBusinessInfo, formDownload } from 'nc-lightapp-front';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import { hrAjax as ajax, saveValidate, getAppPageConfig } from 'src/hrpub/common/utils/utils';
import handdleCheckedData from '../container/functions/checkDataPermissionAction';
import Header from '../components/Header';
import Pagination from '../components/Pagination';
import SignModal from '../components/SignModal';
import EmptyData from "src/hrpub/common/components/emptyImg";
// import {fixedCol} from "../../../../../hrpub/common/utils/utils";
import { chectFormAction, setFormAttrAndValue } from '../../../../public/functions/checkFormAction';
import setAllpks from '../../../../public/functions/setAllpks';
import printPage from './functions/print';
import Export from 'src/hrpub/common/utils/exportHtml';
import ViewCard from 'src/hrpub/common/components/card-view';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
let businessInfo = getBusinessInfo() || {};
// import IsMac from '../../../../public/functions/isMac';
import './index.less';

const { NCButton, NCSelect, NCCheckbox } = base;
const NCOption = NCSelect.NCOption;
// const { NCUploader } = high;

import NCUploader from 'uap/common/components/NCUploader';
let tableid = 'dataList';
let cardId = 'dataCard';
const appcode = getAppPageConfig().appcode, pagecode = getAppPageConfig().pagecode;

const languageId = "sign6011";
const domainName = "hrcm";

class CMSign extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.form('dataCard', 'dataCard_add')
            props.use.editTable('dataList', 'psnList')
            props.use.search('listquery', 'query')
        }
        this.config = {
            pagecode: pagecode,
            appcode: appcode
        };
        this.state = {
            json: {},
            fromApprove: false,         //判断是否从审批中心过来
            pk_org: '',
            showMode: 'browse',
            showUploader: false,        //是否显示附件管理
            isDataListPage: true,       //是否是列表数据页面
            rowsListData: [],           //展示区域数据 
            rowsCardData: [],
            pageType: tableid,
            pageInfo: {
                pageIndex: 1,
                pageSize: 10
            },
            showFlowModal: false,
            conditions: null,
            designateDisplay: false,     //指派
            designateData: ''            //指派人的数据
        }

        props.createUIDom(this.config, (data) => {
            let oid = data.template.listquery.oid;
            this.initMeta(data.template, this, data.button);
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                telName: data.template.name || '',
                oid: oid,
                pageid: data.template.pageid
            });
            props.meta.setMeta(data && data.template ? data.template : {}, () => { });
            props.button.setButtons(data && data.button ? data.button : {});
            console.log('createUIDom...')
            if(!this.hasToCard && this.state.fromApprove){
                this.toCardForm()
            }
        });

        this.saveTableData = this.saveTableData.bind(this);
        this.onHideUploader = this.onHideUploader.bind(this);
        this.submitEvent = this.submitEvent.bind(this);
        this.refreshTableData = this.refreshTableData.bind(this);
        this.closeApproveDetailModal = this.closeApproveDetailModal.bind(this);
        this.fliterListData = this.fliterListData.bind(this);
        this.submitDesignate = this.submitDesignate.bind(this);
        this.hideDesignate = this.hideDesignate.bind(this);
        this.judgeFromWhere = this.judgeFromWhere.bind(this);
        // this.fileInput = React.createRef();
    }

    componentWillMount() {
        // window.location.hash = `?page=2019`;
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({ json, inlt })//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({ moduleId: languageId, domainName: domainName, callback })
        this.judgeFromWhere();
    }

    componentDidMount() {
        this.updateButtonStatus();
        // 计算列表的高度
        let bodyH = this.refs.getContainerDom.offsetHeight;
        let headerH = this.header.getHeaderH();
        this.setState({
            tableHeight: bodyH - headerH - 44
        })
        this.setButtonHidden();
    }

    // 设置所有button隐藏
    setButtonHidden() {
        this.props.button.setButtonVisible(['add', 'edit', 'delete', 'refresh', 'save', 'cancel', 'file', 'query', 'submit', 'revoke', 'history', 'import', 'launch', 'print', 'export_excel', 'cardview' , 'print'], false);
    }

    //初始化meta数据
    initMeta(template, opt, buttonStg) {
        let that = this;
        let { json } = this.state;
        let data = template.dataList.items;
        // fixedCol(template['dataList'], ['contractnum', 'pk_majorcorp','pk_psndoc.code','pk_psndoc'],json['hrcm-000039'])
        // data.unshift({
        //     attrcode: 'index',
        //     itemtype: 'customer',
        //     hyperlinkflag: false,
        //     label: json['hrcm-000039'], // 序号
        //     width: '65px',
        //     textAlign: 'center',
        //     visible: true,
        //     fixed: 'left',
        //     render(text, record, index) {
        //         return (
        //             <span>{index + 1}</span>
        //         )
        //     }
        // });
        data.push({
            attrcode: 'handleArea',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000012'], /* 国际化处理： 操作*/
            width: '250px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let data = record.values;
                let approve_state = data.approve_state.value;
                let signtype = data.signtype.value;
                let sign_state = data.sign_state.value;
                if(signtype === '2'){
                    //判断是否电子合同且状态为4时显示发起操作
                    if( sign_state === '4' && approve_state !== '-1'){
                        return (
                            <div>
                                <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                    onClick={opt.launchOpreation.bind(opt,record)}
                                >
                                    { /* 国际化处理： 发起*/}
                                    { json['hrcm-000043'] }
                                </span>
                                <span style={{color: '#0073E1', cursor: 'pointer'}}
                                    onClick={opt.historyOpreation.bind(opt,record)}
                                >
                                    { /* 国际化处理： 流程历史*/}
                                    { json['hrcm-000044'] }
                                </span>
                            </div>
                        )
                    }else if( sign_state  === '4'){
                        return (
                            <div>
                                <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                    onClick={opt.launchOpreation.bind(opt,record)}
                                >
                                    { /* 国际化处理： 发起*/}
                                    { json['hrcm-000043'] }
                                </span>
                            </div>
                        )
                    }else {
                       return that.judgeRowButton(approve_state, opt, record)
                    }
                }else{
                    return that.judgeRowButton(approve_state, opt, record)
                }
            }
        });
        let isFile = buttonStg.filter(item => item.key === 'file') 
        isFile.length > 0 &&  data.push({
            attrcode: 'opr',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000011'], /* 国际化处理： 附件管理*/
            width: '80px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                return (
                    <a style={{cursor: 'pointer'}}>
                        <i className="icon iconfont icon-fujianshenpi" onClick={() => {
                            opt.attachManage(record);
                        }}/>
                    </a>
                )
            }
        })
    }
    // 判断行操作按钮显示
    judgeRowButton (approve_state, opt, record){
        let { json } = this.state;
        if(approve_state === '-1'){ //自由态
            return (
                <div>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.modifyCheckData.bind(opt,record)}
                    >
                        { /* 国际化处理： 编辑*/}
                        { json['hrcm-000001'] }
                    </span>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.deleteBatchesData.bind(opt,record)}
                    >
                        { /* 国际化处理： 删除*/}
                        { json['hrcm-000014'] }
                    </span>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.isSubmitEvent.bind(opt,record)}
                    >
                        { /* 国际化处理： 提交*/}
                        { json['hrcm-000047'] }
                    </span>
                </div>
            )
        }else if(approve_state === '2' || approve_state === '3'){ //进行中和提交态
            return (
                <div>
                    <span style={{color: '#0073E1', cursor: 'pointer',marginRight: '12px'}}
                        onClick={opt.revokeOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 撤回*/}
                        { json['hrcm-000048'] }
                    </span>
                    <span style={{color: '#0073E1', cursor: 'pointer'}}
                        onClick={opt.historyOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 流程历史*/}
                        { json['hrcm-000044'] }
                    </span>
                </div>
            )
        }else if(approve_state === '0' || approve_state === '1'){
            return (
                <div>
                    <span style={{color: '#0073E1', cursor: 'pointer'}}
                        onClick={opt.historyOpreation.bind(opt,record)}
                    >
                        { /* 国际化处理： 流程历史*/}
                        { json['hrcm-000044'] }
                    </span>
                </div>
            )
        }
    }
    // 判断是否从审批中心过来
    judgeFromWhere (){
        console.log('judgeFromWhere...')
        const { getUrlParam } = this.props;
        let { pk_org, oid } = this.state;
        let id = getUrlParam('id');
        let status = getUrlParam('status');
        let fromApprove = getUrlParam('scene');
        if (!fromApprove && status) {
            fromApprove = 'approvesce'
        }
        if(fromApprove === 'approvesce' || fromApprove === 'notice'){
            this.setState({
                fromApprove: true,
                pk_ctrtmng: id,
                status: status,
                pk_org: businessInfo.groupId,
                isEmpty: false
            },()=>{
                if(oid){
                    this.hasToCard = true;
                    this.toCardForm();
                }
            })
        }
    }

    //筛选单据范围
    fliterListData(conditions){
        this.fetchTableData({conditions});
    }

    // 点击提交事件
    isSubmitEvent(record){
        let { fromApprove } = this.state;
        let pks = this.getPkPsndocSub(record);
        !!pks && handdleCheckedData(pks, appcode, 'submit', fromApprove , ()=>{
            this.submitEvent(pks);
        });
    }

    // 撤回
    revokeOpreation (record){
        let { fromApprove } = this.state;
        // let pks;
        // if (!!v) {
        //     pks = v && v.values.pk_psndoc_sub.value;
        // } else {
        let pks = this.getPkPsndocSub(record);
        // }
        !!pks && handdleCheckedData(pks, appcode, 'delete', fromApprove ,  () => {
            this.revokeAction(pks);
        })
    }

    revokeAction (pks){
        let { isDataListPage, pk_org, json } = this.state;
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngRecallAction.do',
            data: {
                pk_org: pk_org,
                appCode: appcode,
                pk_ctrtmngs: pks
            },
            success: (result) => {
                if (result.success) {
                    toast({color: 'success', content:  json['hrcm-000044'] }); /* 国际化处理： 已撤销*/
                    if( !isDataListPage ){
                        this.getCardFormData(pks);
                    }
                    this.refreshTableData();
                }
            }
        })
    }


    // 流程历史
    historyOpreation(rewRecord){
        const { form } = this.props;
        let { isDataListPage } = this.state; 
        let billid, billtype;
        if (isDataListPage) {
            let recordData = rewRecord.values;
            billid = recordData.pk_ctrtmng.value;
            billtype = recordData.pk_billtype.value
        } else {
            let formData = form.getAllFormValue(cardId).rows[0];
            billid = formData.values.pk_ctrtmng.value;
            billtype = formData.values.pk_billtype.value;
        }
        this.setState({
            showFlowModal: true,
            billid,
            billtype
        })
    }

    // 关闭流程历史
    closeApproveDetailModal(){
        this.setState({
            showFlowModal: false
        })
    }


    //查询设置组织pkorg
    searchOrganizationChange(data) {
        let pkorg = data.refpk;
        this.setState({
            pk_org: pkorg,
            storageOrgData: data
        }, () => {
            // this.getStorageData();
            this.fetchTableData();
        })
    }

    //根据获取本地存储的主键信息获取数据
    // getStorageData() {
    //     let storage = JSON.parse(window.localStorage.getItem('pageQueryParam'));
    //     let storageData = storage && Object.keys(storage);
    //     if (storageData && !!storageData.length) {
    //         let storage_pk = storage && storage.sign && storage.sign.pk_psndoc_subs;
    //         let hrorgobj = storage && storage.sign && storage.sign.hrorgobj;
    //         hrorgobj && this.setState({
    //             pk_org: hrorgobj.refpk,
    //             storage_pk: storage_pk
    //         }, () => {
    //             this.fetchTableData({ key: storage_pk, queryType: 1 });
    //             this.header.setOrganizationValue(hrorgobj);
    //         })
    //     } else {
    //         this.fetchTableData();
    //     }
    // }

    //存储人力资源组织信息
    storageOrgData() {
        let { storageOrgData } = this.state;
        let orgData = {
            sign: {
                hrorgobj: storageOrgData
            }
        }
        orgData && window.localStorage.setItem('pageQueryParam', JSON.stringify(orgData));
    }

    //主键信息格式化
    formatPkPsndocSub(key, areaCode, type) {
        if (key && key.jobpks) {
            if (areaCode != tableid) {
                let len = key.jobpks.length;
                key = key.jobpks[len - 1];
            } else {
                key = [];
            }
        }
        if (key && Object.prototype.toString.call(key) === '[Object Object]' ) {
            key = [key];
        } else if( key ) {
            key = [key];
        } else {
            key = []
        } 
        if (type == 1 && areaCode == tableid) {
            key = []
        }
        return key;
    }

    //数据初始化
    fetchTableData({ key, type, isRefresh, conditions , queryType = 0} = {}) {
        let { pk_org, isDataListPage, pageInfo, json, oid } = this.state;
        let areaCode = tableid;
        // let pkPsndocSub = this.formatPkPsndocSub(key, areaCode, type);
        if (!!pk_org) {
            ajax({
                url: '/nccloud/hrcm/ctrtmng/CtrtMngQueryListAction.do',
                data: {
                    pageCode: pagecode,
                    pk_org: pk_org,
                    areaCode: areaCode,
                    // queryType: queryType,
                    // showSealDataFlag: true,
                    // orgFilter: true,
                    // isNodeCodeFilter: true,
                    // pkPsndocSub: pkPsndocSub,      //卡片状态刷新数据
                    pageInfo: pageInfo,
                    appCode: appcode,
                    ...conditions
                },
                success: res => {
                    if (res.success && res.data) {
                        let data = res.data;
                        let rowsData,allpks;
                        if (isDataListPage) {
                            allpks = data.dataList && data.dataList.allpks || [];
                            rowsData = data && data.dataList.rows;
                            // if(!!rowsData){
                            this.props.button.setButtonVisible(['add', 'delete', 'refresh', 'submit', 'revoke', 'query', 'import', 'launch', 'print', 'export_excel'], true);
                            this.props.button.setButtonVisible(['save', 'cancel', 'edit', 'history', 'cardview'], false);
                            this.props.button.setButtonDisabled(['edit', 'delete', 'refresh', 'submit', 'revoke', 'launch'], false);
                            // }
                            // this.props.button.setButtonDisabled(['add'], false);
                            this.props.editTable.setTableData(tableid, { rows: rowsData || [] });
                            //设置翻页数据
                            this.setState({
                                pageInfo: res.data.dataList.pageInfo,
                                isVisiblePagination: true   //控制翻页显示隐藏
                            })
                            cacheTools.set('allpks', allpks);
                        } else {
                            // rowsData = res.data && res.data.dataCard.rows[0];
                            // if (!!rowsData.values.newifprop.value || rowsData.values.newifprop.value === 'Y') {
                            //     rowsData.values.newifprop.display = json['hrcm-000018'];
                            //     rowsData.values.newifprop.value = 'Y';
                            // } else {
                            //     rowsData.values.newifprop.display = json['hrcm-000019'];
                            //     rowsData.values.newifprop.value = 'N';
                            // }
                            // if (!!rowsData) {
                            //     let formData = {
                            //         rows: new Array(rowsData)
                            //     };
                            //     this.props.form.setAllFormValue({ [cardId]: formData });
                            // }
                            if (!!key && Array.isArray(key)) { //数组是新增过来的数据
                                allpks = cacheTools.get('allpks');
                                if(!!key.jobpks){
                                    key = key.jobpks;
                                }
                                let newAllpks = allpks.concat(key);
                                let len = key.length;
                                newAllpks = Array.from(new Set(newAllpks));
                                cacheTools.set('allpks', newAllpks);
                                this.header.setCardPagination(key[len - 1]);
                            }else if(!!key){      //字符串是删除生效时的数据
                                this.header.setCardPagination(key);
                            }
                            this.hidePagination();
                        }
                    } else {
                        // this.props.button.setButtonVisible(['add','delete','takeEffect', 'refresh'],true);
                        // this.props.button.setButtonVisible(['save','cancel','text','file'],false);
                        this.props.button.setButtonVisible({
                            save: false,
                            cancel: false,
                            text: false,
                            file: false,
                            add: true,
                            delete: true,
                            // takeEffect: true,
                            refresh: true,
                            submit: true,
                            history: false,
                            revoke: true,
                            import: true,
                            cardview: false
                        })
                        this.props.button.setButtonDisabled({
                            edit: true,
                            delete: true,
                            refresh: true,
                            add: false,
                            submit: true,
                            revoke: true
                        })
                        // this.props.button.setButtonDisabled(['edit','delete','takeEffect','refresh'],true);
                        // this.props.button.setButtonDisabled(['add'],false);
                        this.props.editTable.setTableData(tableid, { rows: [] });
                        this.props.form.EmptyAllFormValue(cardId);
                        this.hidePagination();
                        if (isDataListPage) {
                            this.props.button.setButtonDisabled(['refresh'], false);
                            this.props.button.setButtonVisible(['query'],true);
                        } else {
                            this.props.button.setButtonDisabled(['refresh'], true);
                            this.props.button.setButtonVisible(['query'],false);
                        }
                    }
                    if (!!isRefresh) {
                        toast({ color: 'success', content: json['hrcm-000016'] });  /* 国际化处理： 刷新成功！*/
                    }
                    // this.deleteStorage();
                }
            })
        } else {
            // this.props.button.setButtonDisabled(['add','edit','delete','takeEffect','file'],true);
            this.props.button.setButtonVisible(['add', 'edit', 'delete', 'revoke', 'submit', 'refresh', 'query', 'import', 'launch', 'print', 'export_excel', 'cardview'], false);
            this.hidePagination();
        }
    }

    //删除localStorage
    deleteStorage(){
        let pageQueryParamObj = JSON.parse(localStorage.getItem('pageQueryParam'));
        if(!!pageQueryParamObj){
            delete pageQueryParamObj.sign;
            localStorage.setItem('pageQueryParam',JSON.stringify(pageQueryParamObj));
        }
    }

    //列表
    getTableListData() {
        let { pk_org, json } = this.state;
        let tableHeight = this.state.tableHeight;
        if (!!pk_org) {
            return (
                <div className="nc-singleTable-table-area nc-bill-table-area">
                    {this.props.editTable.createEditTable(tableid, {
                        cancelCustomRightMenu: true,
                        showIndex: true, 		//显示序列号
                        showCheck: true,        //显示复选框
                        onRowDoubleClick: this.toCardForm.bind(this),    //编辑表格数据
                        sort: { mode: 'single', backSource: false, sortFun: (v, rows) => { setAllpks(rows, 'pk_ctrtmng') } },
                        // onSelected: this.getSelectedData.bind(this),     //获取选中的数据
                        height: tableHeight - 72    //设置高度
                    })}
                </div>
            )
        } else {
            return (
                <EmptyData text={json['hrcm-000017']}></EmptyData>
            )
        }
    }

    //隐藏列表翻页
    hidePagination() {
        this.setState({
            isVisiblePagination: false   //控制翻页显示隐藏
        })
    }
    //保存
    saveTableData(step) {
        let formData = this.props.form.getAllFormValue(cardId).rows;
        let stepNum = step ? step : '0';
        let { json, pageid, fromApprove } = this.state;
        let pk_ctrtmng = formData[0].values.pk_ctrtmng.value;
        saveValidate(this.props, pageid, cardId, null, 'form').then(()=>{
            if (this.props.form.isCheckNow(cardId)) {
                ajax({
                    url: '/nccloud/hrcm/ctrtmng/CtrtMngUpdateSaveDataAction.do',
                    data: {
                        scene : fromApprove ? 'approvesce' : null,
                        baseParam: {
                            step: stepNum
                        },
                        formData: {
                            model: {
                                rows: formData
                            }
                        }
                    },
                    success: res => {
                        if (res.success && res.data) {
                            let data = res.data;
                            if (data.step == '1') {
                                let content = {
                                    content: data.msg
                                }
                                let fn = {
                                    sureFn: this.saveTableData.bind(this)
                                }
                                this.promptBoxModal(content, fn, '1');
                            } 
                            // else if (data.step == '3') {
                            //     let fn = {
                            //         sureFn: this.isSubmitEvent.bind(this)
                            //     }
                            //     content.sureName = json['hrcm-000018'];
                            //     content.cancelName = json['hrcm-000019'];
                            //     this.refreshTableData();
                            //     this.updateShowMode('browse');
                            //     this.promptBoxModal(content, fn, '3');
                            // }
                            else {
                                toast({color: 'success', content: json['hrcm-000045']});  /* 国际化处理： 保存成功*/
                                this.getCardFormData(pk_ctrtmng);
                                this.updateShowMode('browse');
                                this.setState({
                                    pk_ctrtmng: pk_ctrtmng
                                }, () => {
                                    this.header.setCardPagination(pk_ctrtmng)
                                })
                            }
                        }
                    }
                })
            }
        });
    }

    //操作卡片翻页
    handleCardPagination(pks) {
        this.getCardFormData(pks);
    }

    //确认弹窗
    promptBoxModal(context, fn = {}, args) {    //context 内容；fn 执行的方法；args 传递的参数
        let { sureFn, cancelFn } = fn;
        let { json } = this.state;
        promptBox({
            color: 'warning',                   // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: json['hrcm-000003'],         // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context.content,           // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                    // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,                 // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: context.sureName ? context.sureName : json['hrcm-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: context.cancelName ? context.cancelName : json['hrcm-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn: true,                  //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },       // 确定按钮点击调用函数,非必输
            beSureBtnClick: () => { sureFn && sureFn(args) },       // 确定按钮点击调用函数,非必输
            cancelBtnClick: () => { cancelFn && cancelFn(args) },   // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop: false,        //点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }
    //刷新
    refreshTableData(isRefresh) {
        this.setState({
            isDataListPage: !this.state.isDataListPage ? false : true,
            storage_pk: []
        }, () => {
            if (this.state.isDataListPage) {
                this.fetchTableData({ isRefresh: isRefresh });
            } else {
                let pk_ctrtmng = this.props.form.getAllFormValue(cardId).rows[0].values.pk_ctrtmng.value;
                // this.fetchTableData({ key: pk_ctrtmng, isRefresh: isRefresh });
                this.getCardFormData(pk_ctrtmng);
            }
        })

    }

    //获取某一处修改的数据索引
    searchIndex(arr, id) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].rowid == id) {
                return i;
            }
        }
    }

    // 按钮是否显示，按钮是否可用
    updateButtonStatus() {
        let { showMode, fromApprove } = this.state; 
        if( fromApprove ){
            this.props.button.setButtonsVisible({
                edit: true,
                save: false,
                cancel: false,
                output: false
            })
        }else{
            this.props.button.setButtonsVisible({
                add: showMode === 'browse',
                edit: showMode === 'browse',
                delete: showMode === 'browse',
                text: showMode === 'browse',
                refresh: showMode === 'browse',
                submit: showMode === 'browse',
                // revoke: showMode === 'browse',
                // history: showMode === 'browse',
                save: showMode === 'edit',
                cancel: showMode === 'edit',
                cardview: showMode === 'browse'
            })
        }
    }

    // 更新界面状态
    updateShowMode(showMode) {
        // var oldMode = this.state.showMode;
        let { json, fromApprove } = this.state;
        this.setState({
            showMode: showMode
        }, () => {
            this.updateButtonStatus()
        })
        if ('edit' === showMode) {
            this.props.form.setFormStatus(cardId, 'edit');
        } else {
            // this.props.editTable.cancelEdit(tableid);
            if(!fromApprove){
                this.header.setCardPaginationVisibleFn(true);
            }
            this.props.form.cancel(cardId);
            let formData = this.props.form.getAllFormValue(cardId);
            if (formData && formData.rows[0].values.newifprop && formData.rows[0].values.newifprop.value === 'Y' || formData.rows[0].values.newifprop && formData.rows[0].values.newifprop.value === true) {
                this.props.form.setFormItemsValue(cardId, { 'newifprop': { display: json['hrcm-000018'], value: true, scale: "-1" } })
            } else {
                this.props.form.setFormItemsValue(cardId, { 'newifprop': { display: json['hrcm-000019'], value: false, scale: "-1" } })
            }
            // this.props.form.setFormStatus(cardId,'browse');
        }
    }

    //返回
    handleBackClick() {
        let { storage_pk } = this.state;
        this.setState({
            isDataListPage: true
        }, () => {
            this.props.button.setButtonVisible(['add', 'delete', 'refresh', 'takeEffect', 'query', 'import'], true);
            this.props.button.setButtonVisible(['save', 'cancel', 'text', 'file', 'edit'], false);
            this.fetchTableData({key: storage_pk});
        })
    }

    //进入CardForm
    toCardForm(records) {
        const { button } = this.props;
        let { fromApprove } = this.state;
        button.setButtonVisible(['edit', 'history', 'revoke', 'submit', 'file'], true);
        this.setState({
            isDataListPage: false,
            isVisiblePagination: false //控制翻页显示隐藏
        }, () => {
            let pk_ctrtmngs;
            if(fromApprove){
                let { pk_ctrtmng } = this.state;
                pk_ctrtmngs = pk_ctrtmng;
                button.setButtonVisible({
                    'edit': true,
                    'submit': false,
                    'revoke': false,
                    'history': false,
                    'import': false,
                    'launch': false,
                    'file': true
                });
            }else{
                pk_ctrtmngs = records && records.values.pk_ctrtmng.value;
                this.header.showHeadLeftFn(true, pk_ctrtmngs);
            }
            this.header.getCardFormId(cardId);
            this.getCardFormData(pk_ctrtmngs);
        })
    }

    //进入CardForm展示数据
    getCardFormData(pk_ctrtmng, optType){
        const { form, button } = this.props;
        let { pk_org, json, fromApprove } = this.state;
        this.setButtonHidden();
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngQueryDetailAction.do',
            data: {
                areaCode: cardId,
                pk_org: pk_org,
                appCode: appcode,
                pageCode: pagecode,
                pk_ctrtmng: pk_ctrtmng
            },
            success: (res) => {
                let data = res.data;
                if (res.success && data.detailForm) {
                    let formData = data.detailForm.dataCard;
                    let values =  formData.rows[0].values;
                    let approve_state = values.approve_state.value;
                    let signtype = values.signtype.value;
                    let sign_state = values.sign_state.value;

                    if( fromApprove ){ //来自审批中心的进行中和提交态
                        if( approve_state === '2' || approve_state === '3' ){
                            button.setButtonVisible({
                                edit: true,
                                add: false,
                                submit: false,
                                query: false,
                                delete: false,
                                launch: false,
                                history: false,
                                revoke: false,
                                refresh: false,
                                export_excel: false,
                                cardview: true,
                                output: false,
                                file: true
                            });
                        }else{
                            button.setButtonVisible(['add', 'edit', 'submit', 'query', 'delete', 'launch', 'history', 'revoke', 'refresh', 'export_excel'], false);
                        }
                    }else{
                        //根据单据状态判断肩部按钮的显示
                        if(approve_state === '-1'){ //自由态
                            button.setButtonVisible(['add', 'edit', 'submit', 'delete', 'refresh', 'cardview'], true);
                            button.setButtonVisible([ 'history', 'query', 'revoke' ], false);
                        }else if(approve_state === '2' || approve_state === '3'){ //进行中和提交态
                            button.setButtonVisible(['add', 'history', 'revoke', 'refresh', 'cardview'], true);
                            button.setButtonVisible(['edit', 'query', 'submit', 'delete'], false);
                        }else if(approve_state === '0' || approve_state === '1'){
                            button.setButtonVisible(['add', 'history', 'refresh', 'cardview'], true);
                            button.setButtonVisible(['edit', 'revoke', 'query', 'submit', 'delete'], false);
                        }

                        //判断是否电子合同且状态为4时显示发起操作
                        if( signtype === '2' && sign_state === '4'){
                            button.setButtonVisible(['launch'], true);
                        }else{
                            button.setButtonVisible(['launch'], false);
                        }
                        button.setButtonVisible(['file'], true)
                    }
                    form.setAllFormValue({ [cardId]: formData });
                    // button.setButtonVisible(['edit', 'history', 'revoke', 'submit'], true);
                    // setFormAttrAndValue(data.attrMap, data.valueMap, this.props, cardId, [cardId]);
                    if (optType === 'edit') {
                        this.editCardData(formData);
                    }
                    if (formData && formData.rows[0].values.newifprop.value === 'Y' || formData && formData.rows[0].values.newifprop.value === true) {
                        form.setFormItemsValue(cardId, { 'newifprop': { display: json['hrcm-000018'], value: true, scale: "-1" } })
                    } else {
                        form.setFormItemsValue(cardId, { 'newifprop': { display: json['hrcm-000019'], value: false, scale: "-1" } });
                        form.setFormItemsDisabled(cardId, { 'promonth': true, 'prop_unit': true, 'probegindate': true, 'probenddate': true });
                    }
                    this.handleEditFormDate(this.props, cardId, '');
                }
            }
        })
    }

    // 修改数据校验事件
    modifyCheckData(record) {
        let { isDataListPage, fromApprove } = this.state;
        let pk_ctrtmng;
        if (isDataListPage) {
            pk_ctrtmng = record.values.pk_ctrtmng.value;
        } else {
            let formCardData = this.props.form.getAllFormValue(cardId);
            pk_ctrtmng = formCardData && formCardData.rows[0].values.pk_ctrtmng.value;
        }
        handdleCheckedData(pk_ctrtmng, appcode, 'edit', fromApprove, () => {
            if (isDataListPage) {
                this.modifyListData(pk_ctrtmng);
            } else {
                this.editCardData();
            }
        });
    }

    //修改列表数据
    modifyListData(pk_ctrtmng){
        let { form } = this.props;
        let { json } = this.state;
        // let formData = v;
        this.setState({
            isDataListPage: false,
            isVisiblePagination: false
        },()=>{
            this.header.showHeadLeftFn(true,pk_ctrtmng);
            this.getCardFormData(pk_ctrtmng, 'edit');
            this.editCardData();
        });
    }

    //编辑卡片时数据
    editCardData() {
        let { json, pk_org } = this.state;
        let extendParam = {
            pk_org: pk_org
        }
        this.props.form.setFormStatus(cardId, 'edit');
        this.props.button.setButtonVisible(['add', 'edit', 'delete', 'refresh', 'submit', 'revoke', 'history', 'query', 'cardview', 'file'], false);
        this.props.button.setButtonVisible(['save', 'cancel'], true);
        this.header.setCardPaginationVisibleFn(false);
        this.header.getCardFormId(cardId);
    }

    //卡片日期设置
    handleEditFormDate(props, moduleId, key, value) {
        let url = '/nccloud/hrcm/ctrtmng/CtrtMngFormAfterEditAction.do';
        props.formId = !!key? '' : 'signaplly'; // 编辑后事件和保存接口 赋值的时候写法不一致， 不然保存接口返回的数据有部分不显示
        chectFormAction(key, moduleId, props, [cardId], appcode, '', url);
    }

    //form编辑前事件
    handleEditBefore(props, moduleId, key, value,data){
        if(key == 'newpk_conttext'){
            let that = this;
            let meta = that.props.meta.getMeta();
            let pk_org = this.state.pk_org;
            meta[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            that.props.meta.setMeta(meta);
        }
        return true;
    }

    //获取主键
    getPkPsndocSub(record) {
        let { isDataListPage, json } = this.state;
        let pks = [];
        if (!isDataListPage) {
            pks = this.props.form.getAllFormValue(cardId).rows[0].values.pk_ctrtmng.value;
        } else {
            if(!!record){
                pks.push(record.values.pk_ctrtmng.value);
            }else{
                let checkedData = this.props.editTable.getCheckedRows(tableid);
                if (!checkedData.length) {
                    toast({ color: 'warning', content: json['hrcm-000020'] });
                    return;
                }
                checkedData.map((v) => {
                    pks.push(v.data.values.pk_ctrtmng.value);
                })
            }
        }
        return pks;
    }

    //提交
    submitEvent(pks, designateData = null) {
        let pageType = '';
        let { isDataListPage, json, storage_pk, pk_org } = this.state;
        // debugger
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngSubmitAction.do',
            data: {
                pk_org: pk_org,
                appCode: appcode,
                pk_ctrtmngs: pks,
                ...designateData
            },
            success: res => {
                if (res.success) {
                    if (res.data && res.data.content) {
                        this.setState({
                            designateDisplay: true,
                            designateData: res.data.content,
                            pk_ctrtmngsData: pks
                        })
                        return;
                    }else{
                        toast({
                            color: 'success',
                            content: json['hrcm-000050'] /* 国际化处理： 提交成功*/
                        });
                        this.hideDesignate();
                    }
                    if( !isDataListPage ){
                        this.getCardFormData(pks);
                        this.updateShowMode('browse');
                    }
                    this.refreshTableData();
                }
            }
        })
    }

    //如果有指派调用此方法
    submitDesignate (value){
        let { pk_ctrtmngsData } = this.state;
        let designateData = {
            // billIds : billIds,
            content: value
        }
        this.submitEvent(pk_ctrtmngsData, designateData);
    }

    //关闭指派
    hideDesignate (){
        this.setState({
            designateDisplay: false
        })
    }

    // 关闭附件
    onHideUploader() {
        this.setState({
            showUploader: false
        })
    };

    //批量删除
    deleteBatchesData(record) {
        let { fromApprove } = this.state;
        let pks = this.getPkPsndocSub(record);
        !!pks && handdleCheckedData(pks, appcode, 'delete', fromApprove, () => {
            this.delPrompt(pks)
        });
    }

    // 删除确认弹窗
    delPrompt(pks) {
        let fn = {
            sureFn: () => { this.deleteData(pks) }
        }
        let content = {
            content: this.state.json['hrcm-000021']
        }
        this.promptBoxModal(content, fn);
    }

    //删除数据
    deleteData(PKsData) {
        let { storage_pk, isDataListPage, pk_org } = this.state;
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngDeleteAction.do',
            data: {
                pk_ctrtmngs: PKsData,
                appCode: appcode,
                pk_org: pk_org
            },
            success: res => {
                if (res.success && res.data) {
                    if (!isDataListPage) {
                        let allpks = cacheTools.get('allpks') || [];
                        let index = 0;
                        let len = allpks.length;
                        len && allpks.forEach((v, i) => {
                            if (v == PKsData) {
                                allpks.splice(i, 1);
                                if (i < len - 1) {
                                    index = i;
                                } else if (i == len - 1) {
                                    index = i - 1;
                                }
                            }
                        })
                        cacheTools.set('allpks', allpks);
                        this.getCardFormData(allpks[index]);
                        this.fetchTableData({key: allpks[index]});
                    } else {
                        this.fetchTableData({key: storage_pk});
                    }
                }
            }
        })
    }

    //操作翻页方法
    changePagination(pageInfo) {
        const {conditions} = this.state
        this.setState({
            pageInfo
        }, () => {
            this.fetchTableData({conditions});
        })
    }

    //改变每页展示数据量
    pageSizeSelect(pageInfo) {
        const {conditions} = this.state
        this.setState({
            pageInfo
        }, () => {
            this.fetchTableData({conditions});
        })
    }

    //取消编辑态
    cancelEditStatus() {
        let { json } = this.state;
        let fn1 = {
            sureFn: this.updateShowMode.bind(this)
        }
        let content = {
            content: json['hrcm-000022']
        }
        this.promptBoxModal(content, fn1, 'browse');
    }

    //附件管理
    attachManage(record) {
        let { fromApprove } = this.state;
        let billId, billNo;
        if (!!record) {
            billId = record.values.pk_ctrtmng.value;
            // billNo = record.values.contractnum.value
        } else {
            let cardData = this.props.form.getAllFormValue(cardId).rows[0].values;
            billId = cardData.pk_ctrtmng.value;
            // billNo = cardData.newcontractnum.value;
        }
        handdleCheckedData(billId, appcode, 'attachment', fromApprove, () => {
            this.setState({
                showUploader: true,
                billId: billId,
                // billNo: billNo
            })
        });
    }

    //打开查询
    listQuery () {
        let { pk_org } = this.state;
        this.props.search.openAdvSearch('listquery', true, ()=>{
            let meta = this.props.meta.getMeta();
            let items = meta.listquery.items;
            items.length > 0 && items.map((item,index)=>{
                if(item.attrcode === 'pk_psnjob.pk_dept'){
                    item.queryCondition = {
                        pk_hrorg: pk_org
                    }
                }else if(item.attrcode === 'pk_conttext'){
                    item.queryCondition = {
                        pk_org: pk_org,
                        GridRefActionExt: 'nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder'
                    }
                }
            })
            this.props.meta.setMeta(meta);
        });
    }
    // 查询数据
    searchData = () => {
        // let conditions = props.search.getAllSearchData('query').conditions || [];
        let getConditions = this.props.search.getQueryInfo('listquery',true);
        let conditions = getConditions;
        this.fetchTableData({conditions: conditions});
        this.setState({
            conditions
        })
    }

    // 打开公示
    openPublicity (){
        window.top.openNew({appcode: '60654090'});
    }

    // 导入
    importAction(){
        var file = document.getElementById('inputFile');
        file.click();
    }

    // 导出模板
    export_excelAction(){
        formDownload({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngExportTempletAction.do',
            enctype: 2
        })
    }

    // 点击发起校验
    launchOpreation(record){
        let { fromApprove } = this.state;
        let pks = this.getPkPsndocSub(record);
        !!pks && handdleCheckedData(pks, appcode, 'sendstart', fromApprove , ()=>{
            this.launchAction(pks);
        });
    }

    //发起
    launchAction(PKsData){
        let { isDataListPage, pk_org, json } = this.state;
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngSendStartAction.do',
            data: {
                pk_ctrtmngs: PKsData,
                appCode: appcode,
                pk_org: pk_org
            },
            success: res => {
                if (res.success && res.data) {
                    toast({
                        color: 'success',
                        content: json['hrcm-000051']  /* 国际化处理： 发起成功*/ 
                    });
                    if( !isDataListPage ){
                        this.getCardFormData(PKsData);
                        this.updateShowMode('browse');
                    }
                    this.refreshTableData();
                }
            }
        })
    }

    //打印
    printAction (){
        let { json } = this.state;
        printPage.call(this,tableid, json);
    }

    //输出
    outputAction (){
        let { json } = this.state;
        Export(document.querySelector('.u-table-scroll'),
        {
            title: this.state.telName /* 国际化处理： 合同签订申请*/,
            fileName: this.state.telName + json['hrcm-000002'] /* 国际化处理： 数据*/,
            maker: json['hrcm-000004'] /* 国际化处理： 制单人*/,
            date: json['hrcm-000005'] /* 国际化处理： 制表日期*/
        }, {
            data: this.props.editTable.getAllData(tableid).rows,
            meta: this.props.meta.getMeta()[tableid],
            showIndex: false
        });
    }

    //联查卡片
    showCardview (){
        const { form } = this.props;
        let { pk_org } = this.state;
        let formData = form.getAllFormValue(cardId).rows;
        // this.cardView.openCardViewModal(formData);
        this.wpsview.openView(formData)
    }


    // 统一处理按钮事件
    onBtnOperation(props, btncode) {
        switch (btncode) {
            case 'add':
                this.signNode.showNewIncreased(true)
                break;
            case 'edit':
                this.modifyCheckData();
                break;
            case 'delete':
                this.deleteBatchesData();
                break;
            case 'text':
                let cardData = this.props.form.getAllFormValue(cardId);
                let pk_ctrtmng = cardData.rows[0].values.pk_ctrtmng.value;
                this.contractText(pk_ctrtmng);
                break;
            case 'refresh':
                this.refreshTableData(true);
                break;
            case 'save':
                this.saveTableData();
                break;
            case 'cancel':
                this.cancelEditStatus();
                break;
            case 'import':
                this.importAction();
                break;
            case 'export_excel':
                this.export_excelAction();
                break;
            case 'file':
                this.attachManage();
                break;
            case 'query': 
                this.listQuery();
                break;

            case 'history':
                this.historyOpreation();
                break;
            case 'revoke':
                this.revokeOpreation();
                break;
            case 'submit':
                this.isSubmitEvent();
                break;
            case 'publicity': 
                this.openPublicity();
                break;
            case 'launch':
                this.launchOpreation();
                break;
            case 'print':
                this.printAction();
                break;
            case 'output':
                this.outputAction();
                break;
            case 'cardview':
                this.showCardview();
                break;
            default:
                break;
        }
    }
    render() {
        let { button, editTable, cardPagination, search, form } = this.props;
        const { createCardPagination } = cardPagination;
        let { createButtonApp } = button;
        let { createEditTable } = editTable;
        let { NCCreateSearch } = search;
        let { createForm } = form;
        let { pageInfo, isVisiblePagination, isDataListPage, rowData, pk_org, showUploader, billId, json, oid, billtype, billid, showFlowModal, fromApprove, designateData, designateDisplay} = this.state;
        return (
            <div className="nc-single-table nc-bill-card" ref="getContainerDom">
                <Header
                    {...this.props}
                    ref={node => {
                        this.header = node
                    }}
                    fromApprove = {fromApprove}
                    pk_org = { pk_org }
                    json = { json }
                    onBtnOperation={this.onBtnOperation.bind(this)}
                    handleBackClick={this.handleBackClick.bind(this)}
                    searchOrganizationChange={this.searchOrganizationChange.bind(this)}
                    handleCardPagination={this.handleCardPagination.bind(this)}
                    cancelEditStatus={this.cancelEditStatus.bind(this)}
                    fliterListData={this.fliterListData}
                >
                </Header>
                <div className="content">
                    {/* 生成表格 */}
                    {isDataListPage ? this.getTableListData() :
                        <div className="header-cardPagination-area">
                            {createForm(cardId, {
                                useFixedHeader: true,
                                onAfterEvent: this.handleEditFormDate.bind(this),
                                onBeforeEvent: this.handleEditBefore.bind(this)
                                // onBeforeEvent: this.handleEditFormDateBefore.bind(this)
                            })}
                        </div>
                    }
                    {/* 操作翻页 */}
                    <Pagination
                        {...this.props}
                        pageInfo={pageInfo}
                        isVisiblePagination={isVisiblePagination}
                        changePagination={this.changePagination.bind(this)}
                        pageSizeSelect={this.pageSizeSelect.bind(this)}
                    />
                </div>
                <div style={{display: "none"}}>
                    {
                        NCCreateSearch('listquery', {
                            clickSearchBtn: ()=>{ this.searchData() },
                            onlyShowAdvArea: false,
                            showAdvSearchPlanBtn: true,
                            saveSearchPlan: true,
                            oid: oid,
                            onlyShowSuperBtn: true
                        })
                    }
                </div>
                {/* 调用新增组件 */}
                <SignModal
                    {...this.props}
                    pkOrg={pk_org} //组织编码必传
                    ref={node => {
                        this.signNode = node
                    }}
                    appCode= {appcode}
                    pageCode= {pagecode}
                    nodeType={'sign'}
                    isDataListPage={isDataListPage}
                    getCardFormData = {this.getCardFormData.bind(this)}
                    fetchTableData={this.fetchTableData.bind(this)}
                    storageOrgData={this.storageOrgData.bind(this)}
                />
                {/* 附件管理 */}
                {showUploader && <NCUploader
                    uploadTitle={this.state.json["cm6011-000062"] /*多语: 附件管理*/}
                    billId={billId}
                    // billNo={billNo}
                    placement={'top'}
                    // getGroupList = {this.getGroupList}
                    onHide={this.onHideUploader} // 关闭功能
                // beforeUpload={this.beforeUpload} 
                />
                }
                <ApproveDetail
                    show={showFlowModal}
                    close={this.closeApproveDetailModal}
                    billtype={billtype}  //billMessage.billtype
                    billid={billid}  //billMessage.billid
                />
                {/* 联查卡片 */}
                <ViewCard
                    { ...this.props }
                    onRef ={ (ref) => {
                        this.cardView = ref
                    }}
                ></ViewCard>
                <WpsModal
                        {...this.props}
                        onRef ={node => this.wpsview = node}
                        appcode={appcode}
                        pk_org={pk_org}
                    
                    />
                {/* 指派 */}
                { designateDisplay ? <ApprovalTrans
                    // title={json['hrcm-000069']}/* 国际化处理： 指派*/
                    data={designateData}
                    display={designateDisplay}
                    getResult={this.submitDesignate}
                    cancel={this.hideDesignate}
                /> : null}
                <input 
                    type="file"
                    name='file' 
                    id="inputFile"
                    style={{display: 'none'}}
                />
            </div>
        );
    }
}

export default CMSign;
